const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🧪 测试登录日志功能')
  
  try {
    const { OPENID } = cloud.getWXContext()
    
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败'
      }
    }
    
    console.log('👤 用户OPENID:', OPENID)
    
    // 测试数据库连接
    console.log('🔍 测试数据库连接...')
    
    // 尝试查询现有的登录日志
    const existingLogs = await db.collection('user_login_logs')
      .where({ openid: OPENID })
      .orderBy('loginTime', 'desc')
      .limit(5)
      .get()
    
    console.log('📊 现有登录日志数量:', existingLogs.data.length)
    
    // 创建测试登录日志
    const testLog = {
      openid: OPENID,
      loginType: 'test',
      loginTime: new Date(),
      clientIP: 'test_ip',
      deviceInfo: {
        platform: 'test_platform',
        system: 'test_system',
        version: 'test_version',
        model: 'test_model',
        brand: 'test_brand',
        screenWidth: 375,
        screenHeight: 667,
        pixelRatio: 2
      },
      locationInfo: {
        province: '测试省',
        city: '测试市',
        country: '中国'
      },
      userInfo: {
        nickName: '测试用户',
        avatarUrl: '',
        gender: 0,
        language: 'zh_CN'
      },
      sessionId: `test_${Date.now()}`,
      userAgent: 'test_user_agent',
      createTime: new Date()
    }
    
    console.log('📝 准备插入测试日志:', testLog)
    
    // 插入测试日志
    const insertResult = await db.collection('user_login_logs').add({
      data: testLog
    })
    
    console.log('✅ 测试日志插入成功:', insertResult._id)
    
    // 再次查询验证
    const newLogs = await db.collection('user_login_logs')
      .where({ openid: OPENID })
      .orderBy('loginTime', 'desc')
      .limit(5)
      .get()
    
    console.log('📊 插入后登录日志数量:', newLogs.data.length)
    
    // 测试用户表操作
    console.log('👥 测试用户表操作...')
    
    const userResult = await db.collection('users')
      .where({ openid: OPENID })
      .get()
    
    if (userResult.data.length > 0) {
      console.log('👤 找到现有用户记录')
      const user = userResult.data[0]
      await db.collection('users')
        .doc(user._id)
        .update({
          data: {
            lastLoginTime: testLog.loginTime,
            lastLoginIP: testLog.clientIP,
            loginCount: (user.loginCount || 0) + 1,
            updateTime: new Date()
          }
        })
      console.log('✅ 用户记录更新成功')
    } else {
      console.log('👤 创建新用户记录')
      await db.collection('users').add({
        data: {
          openid: OPENID,
          lastLoginTime: testLog.loginTime,
          lastLoginIP: testLog.clientIP,
          loginCount: 1,
          createTime: new Date(),
          updateTime: new Date()
        }
      })
      console.log('✅ 新用户记录创建成功')
    }
    
    return {
      success: true,
      message: '登录日志测试完成',
      data: {
        openid: OPENID,
        testLogId: insertResult._id,
        existingLogsCount: existingLogs.data.length,
        newLogsCount: newLogs.data.length,
        testLog: testLog,
        allLogs: newLogs.data
      }
    }
    
  } catch (error) {
    console.error('❌ 测试登录日志失败:', error)
    return {
      success: false,
      error: error.message || '测试失败',
      details: error.stack
    }
  }
}
